/* eslint-disable camelcase */
import React, { useEffect, useRef, useState } from 'react';
import { Icon, Dropdown, Menu, Popover, Modal, message, Spin } from 'antd';
import { removeNode, reloadNode, closeNode, nodeInfo } from '@api/nodes';
import { SettingIcon, RunTime, More, AddScan } from './iconSvg.js';
import runningImg from '../../../images/running.png';
import stopImg from '../../../images/stop.png';
import { withRouter } from 'react-router';
import AddNode from '../add-node.js';
import PropTypes from 'prop-types';
import moment from 'moment';
import _ from 'lodash';
import './index.less';

const prefixCls = 'new-node-card';
const { confirm } = Modal;

// eslint-disable-next-line react/prop-types
const NodeCard = ({ list, onOk, singer, history }) => {
  const [visible, setVisible] = useState(false);
  const [detail, setDetail] = useState({});
  // eslint-disable-next-line
  const [obj, forceRender] = useState(-1);
  const dataListRef = useRef(list);

  const jumpToDetail = (type, ip, name) => {
    // eslint-disable-next-line react/prop-types
    history.push('/system-config/equipment-load', { type: type, ip: ip, name: name });
  };

  const confirmModal = (type, item) => {
    const dict = {
      reboot: {
        title: '确认重启？重启过程中将不能访问系统，执行中的任务将受到影响',
        api: reloadNode,
        body: {
          node_ip: _.get(item, 'node_ip')
        },
        operateType: 'reload'
      },
      poweroff: {
        title: '确认关机？关机后将不能访问系统，执行中的任务将受到影响',
        api: closeNode,
        body: {
          node_ip: _.get(item, 'node_ip')
        }
      },
      logout: {
        title: '确定要将该节点移出集群？移出后该节点将不会在产品页面展示，执行中的任务将受到影响',
        api: removeNode,
        body: {
          node_ip: _.get(item, 'node_ip')
        },
        operateType: 'remove'
      }
    };
    const { title, api, body, operateType } = dict[type];
    // 判断是否为管理节点或者单机节点的重启
    let isMasterOrSingleReload =
      ['master', 'single'].includes(_.get(item, 'node_role')) && operateType === 'reload';

    let isOnOfflineRemove = _.get(item, 'status') === 'offline' && operateType === 'remove';

    let OnOfflineRemoveTitle =
      '确定要将该节点移出集群？由于管理节点无法访问该节点，强制移出后该节点将无法自动恢复成单机设备(无法单独访问功能界面)，建议等节点正常后再移出';

    confirm({
      title: isOnOfflineRemove ? OnOfflineRemoveTitle : title,
      className: `${prefixCls}-confirm-modal`,
      width: 500,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        await api(body)
          .then(() => {
            message.success('操作成功');
            Modal.destroyAll();
            onOk();
          })
          .catch(() => {
            // 管理节点或者单机节点重启都会报错
            !isMasterOrSingleReload && message.error('操作失败');
          })
          .finally(() => {
            // 管理节点或者单机节点重启直接关闭弹窗
            if (isMasterOrSingleReload) {
              Modal.destroyAll();
            }
          });
      },
      onCancel() {}
    });
  };
  const menu = item => {
    let isSlave = _.get(item, 'node_role') === 'slave';
    return (
      <Menu style={{ width: 120 }}>
        <Menu.Item key="reboot">
          <div
            onClick={() => {
              confirmModal('reboot', item);
            }}
          >
            <Icon type="redo" className="mr8" style={{ transform: 'rotateZ(-90deg)' }} />
            &nbsp;重启
          </div>
        </Menu.Item>
        <Menu.Item key="poweroff">
          <div
            onClick={() => {
              confirmModal('poweroff', item);
            }}
          >
            <Icon type="poweroff" className="mr8" />
            &nbsp;关机
          </div>
        </Menu.Item>
        {item.node_role !== 'single' && (
          <Menu.Item key="reboot">
            <>
              <div
                onClick={() => {
                  setVisible(true);
                  setDetail(item);
                }}
              >
                <Icon type="edit" className="mr8" />
                &nbsp;编辑
              </div>
            </>
          </Menu.Item>
        )}
        {isSlave && (
          <Menu.Item key="logout">
            <div
              onClick={() => {
                confirmModal('logout', item);
              }}
            >
              <Icon type="logout" className="mr8" />
              &nbsp;移除集群
            </div>
          </Menu.Item>
        )}
      </Menu>
    );
  };

  // 每获取一个节点数据就修改ref中对应的节点值, 然后执行forceRender
  const getNodeInfoAndRender = async () => {
    for (let node of list) {
      nodeInfo(node.node_ip).then(result => {
        const nodeInfo = result?.data?.data;
        // eslint-disable-next-line
        let index = list.findIndex(i => i.node_ip === nodeInfo?.node_ip);
        dataListRef.current[index] = { ...dataListRef.current[index], ...nodeInfo };
        forceRender(index);
      });
    }
  };

  useEffect(() => {
    if (list.length > 0) {
      dataListRef.current = list;
      !singer && getNodeInfoAndRender();
    }
  }, [list]);

  return (
    <>
      {dataListRef.current.map((r, i) => {
        const isMaster = r.node_role !== 'slave';
        const isSingle = r.node_role === 'single' && singer;
        const duration = moment.duration(_.get(r, 'boot_time', 0), 'seconds');
        const formattedTime = `${duration.days()}天${duration.hours()}小时${duration.minutes()}分钟`;
        let status = r.status === 'online';
        return (
          <div className={`${prefixCls} `} key={i}>
            <Spin spinning={false}>
              <>
                <div className={`${prefixCls}-header ${isMaster ? 'single' : 'slave'}`}>
                  <div>
                    <div style={{ color: '#1E1F23' }}>{r.node_ip}</div>
                    <span>{r.node_name}</span>
                  </div>
                  <Popover content={status ? '运行中' : '连接异常'}>
                    <div className={`${prefixCls}-status ${status ? 'running' : ''}`}>
                      <img src={status ? runningImg : stopImg} width="35px" />
                    </div>
                  </Popover>
                </div>
                <div className={`${prefixCls}-content`}>
                  {!isSingle && (
                    <div className={`${prefixCls}-content-item`}>
                      <SettingIcon />
                      <span>节点类型:{isMaster ? '管理节点' : '扫描节点'}</span>
                    </div>
                  )}
                  <div className={`${prefixCls}-content-item`}>
                    <RunTime />
                    <span>设备运行时间：{r.time || formattedTime}</span>
                  </div>
                </div>
                <div className={`${prefixCls}-footer`}>
                  <div className={`${prefixCls}-footer-message`}>
                    <div className="df">
                      <span
                        className={`${prefixCls}-footer-message-link flex1`}
                        onClick={() => jumpToDetail('1', r.node_ip, r.node_name)}
                      >
                        查看系统负载
                      </span>
                      <span
                        className={`${prefixCls}-footer-message-link flex1`}
                        onClick={() => jumpToDetail('2', r.node_ip, r.node_name)}
                      >
                        查看业务负载
                      </span>
                      <span className={`${prefixCls}-footer-operate flex2 pointer`}>
                        <Dropdown
                          overlay={menu(r)}
                          placement="bottomCenter"
                          trigger={['click']}
                          className={`${prefixCls}-footer-operate`}
                        >
                          <span type="menu" className="pointer">
                            <i className={`${prefixCls}-vsub mr5 `}>
                              <More />
                            </i>
                            更多操作
                          </span>
                        </Dropdown>
                      </span>
                    </div>
                  </div>
                </div>
              </>
            </Spin>
          </div>
        );
      })}
      {!singer && (
        <div className={`${prefixCls} `}>
          <div
            className={`${prefixCls}-content-add-card`}
            onClick={() => {
              // form?.current && form.current.resetFields()
              setDetail({});
              setVisible(true);
            }}
          >
            <div className="pointer" style={{ textAlign: 'center' }}>
              <AddScan />
            </div>
          </div>
        </div>
      )}
      <AddNode
        visible={visible}
        detail={detail}
        onCancel={() => {
          setVisible(false), setDetail({});
        }}
        onOk={() => {
          setVisible(false);
          onOk();
        }}
      />
    </>
  );
};

NodeCard.propTypes = {
  singer: PropTypes.bool,
  onOk: PropTypes.func,
  list: PropTypes.array
};

export default withRouter(NodeCard);
